import { Loader } from "@googlemaps/js-api-loader"

export default {
  data() {
    return {
      map: '',
      // 位置格式 {address: '', latitude: '', longitude: ''}
      startPointObj: {}, // 开始位置信息
      endPointObj: {}, // 结束位置信息
	  blinkingCircleOverlay: null
    };
  },
  methods: {
    async loadMap(latitude, longitude, domId = 'map',showInfoWindow = false,) {
      // 引入Google Maps API
      const loader = new Loader({
        apiKey: "AIzaSyCO_aRinQbO9DZXyCje6dyRvxAmvq-82eo",
        version: "weekly",
        libraries: ['places', 'geometry']
      });
      await loader.load().then(async () => {
        const { Map } = await google.maps.importLibrary("maps");

        this.map = new Map(document.getElementById(domId), {
          center: { lat: latitude || 39.909, lng: longitude || 116.39742 },
          zoom: 8,
          fullscreenControl: false,// 隐藏全屏控件
          streetViewControl: false, // 隐藏街景（小人）按钮
          mapTypeControl:false,
          minZoom: 2,
          maxZoom: 16,
          //限制拖拽范围，防止出现除地图外的灰色区域
          restriction: {
            latLngBounds: {
              north: 85,
              south: -85,
              east: 180,
              west: -180,
            },
          }
        });
        // 尝试获取当前位置
        if (navigator.geolocation) {
          let that = this
          navigator.geolocation.getCurrentPosition(
            function(position) {
              let pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
              };
              // 设置地图中心为当前位置s
              that.map.setCenter(pos);
			  // 设置地图的缩放级别
			  that.map.setZoom(15); // 设置为你想要的缩放级别
              // 添加当前位置的标记
              const marker = new google.maps.Marker({
                position: pos,
                map: that.map,
                title: '当前位置',
				icon: {
				  url: '../static/my-position.png',
				  scaledSize: new google.maps.Size(30, 35), // 图标的大小
				  origin: new google.maps.Point(0, 0), // 图标中心的偏移量
				  anchor: new google.maps.Point(15, 15) // 图标的锚点，通常是图标中心
				}
              });
			  // 添加当前位置的标记
			  marker.setMap(that.map);

			  if (that.showInfoWindow) {
				const infoWindow = new google.maps.InfoWindow({
				  content: `
				  <view class="callInfo">
					正在为您呼叫...
				  </view>`
				});
				infoWindow.open(that.map, marker);
				
				// 创建闪烁的圈圈覆盖层
				that.blinkingCircleOverlay = new google.maps.OverlayView();
				that.blinkingCircleOverlay.onAdd = function() {
				  const circleDiv = document.createElement('div');
				  const subCircleDiv = document.createElement('div');
				  circleDiv.classList.add('call-loading');
				  subCircleDiv.classList.add('sub-loading');
				  circleDiv.appendChild(subCircleDiv);
				  this.getPanes().overlayMouseTarget.appendChild(circleDiv);
				};
				
				that.blinkingCircleOverlay.draw = function() {
				  const position = this.getProjection().fromLatLngToDivPixel(marker.getPosition());
				  const circleDiv = this.getPanes().overlayMouseTarget.querySelector('.call-loading');
				  const circleWidth = 188; // 圆圈的宽度
				  const circleHeight = 188; // 圆圈的高度
				
				  // 设置圆圈的位置，使其中心对齐到标记点
				  circleDiv.style.left = (position.x - circleWidth / 2) + 'px';
				  circleDiv.style.top = (position.y - circleHeight / 2) + 'px';
				};
				
				that.blinkingCircleOverlay.setMap(that.map);
			  }
              // const geocoder = new google.maps.Geocoder();
              // geocoder.geocode({'location': pos}, function(results, status) {
              //   if (status === 'OK') {
              //     console.log(results)
              //       if (results[0]) {
              //         console.log('Street Address: ' + that.getAddressComponent(results[0], 'route'));
              //         // 可以在此处将地址显示在页面上
              //         that.startPoint = that.getAddressComponent(results[0], 'route') || results[0].formatted_address
              //       } else {
              //           console.log('No results found');
              //       }
              //   } else {
              //       console.log('Geocoder failed due to: ' + status);
              //   }
              // });
              // 搜索附近的 POI
              that.searchPOI(pos)
            },
            function() {
              console.log('errorCallback')
              that.handleLocationError(true, that.map.getCenter());
            }
          );
        } else {
          // 浏览器不支持地理位置
          console.log('浏览器不支持地理位置')
          that.handleLocationError(false, that.map.getCenter());
        }
      }).catch((err) => {
        console.log('error:', err);
      });
    },
    handleLocationError(browserHasGeolocation, pos) {
      const infoWindow = new google.maps.InfoWindow({
        map: this.map,
        position: pos,
        content: browserHasGeolocation ?
          'Error: The Geolocation service failed.' :
          'Error: Your browser doesn\'t support geolocation.'
      });
    },
    // 搜索附近的poi
    searchPOI(pos) {
      const that = this
      let service = new google.maps.places.PlacesService(this.map);
      service.nearbySearch({
          location: pos,
          radius: 500, // 搜索半径，单位为米
          type: ['point_of_interest'] // 搜索类型为兴趣点
      }, function(results, status) {
          if (status === google.maps.places.PlacesServiceStatus.OK) {
            if (results[0]) {
              that.startPointObj = {
                address: results[0].name,
                latitude: results[0]?.geometry?.location.lat(),
                longitude: results[0]?.geometry?.location.lng()
              }
            }
          }
      });
    },
    // 模糊查询地址
    getPlacesList(text) {
      return new Promise(async(resolve, reject) => {
        if (!text) resolve([])
        if (!this.map) {
          await this.loadMap()
        }
        const autocomplete = new google.maps.places.AutocompleteService();
        autocomplete.getPlacePredictions({ input: text }, function(predictions, status) {
          if (status == google.maps.places.PlacesServiceStatus.OK) {
            resolve(predictions);
          } else {
            resolve([])
          }
        });
      });
    },
    // 根据PlaceId获取详细地址
    async getDetailByPlaceId(placeId) {
      return new Promise(async(resolve, reject) => {
        if (!placeId) resolve()
        if (!this.map) {
          await this.loadMap()
        }
        const request = {
          placeId: placeId,
          fields: ['geometry.location'],
        };
        await new google.maps.places.PlacesService(this.map)?.getDetails(request, (place, status) => {
          if (status === google.maps.places.PlacesServiceStatus.OK) {
            const location = place.geometry.location;
            resolve({
              latitude: location.lat(),
              longitude: location.lng()
            })
          } else {
            resolve()
            console.error('Place details request failed due to:', status);
          }
        });
      });
    },
    // 查询两个经纬度之间的距离，返回单位km
    async calculateDistance(start, end) {
      if (!start || !end) {
        return ''
      }
      if (!this.map) {
        await this.loadMap()
      }
      const latLngA = new google.maps.LatLng(start.latitude, start.longitude); // 替换为第一个经纬度
      const latLngB = new google.maps.LatLng(end.latitude, end.longitude); // 替换为第二个经纬度

      const distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, latLngB);
      // 将距离从米转换为公里
      return Number((distance / 1000).toFixed(2));
    },
	convertTimestampToTime(timestamp) {
		  // 创建一个新日期对象，使用时间戳（毫秒）
		  var date = new Date(timestamp);

		  // 获取小时和分钟
		  var hours = date.getHours();
		  var minutes = date.getMinutes();

		  // 格式化小时和分钟，确保总是两位数
		  hours = hours.toString().padStart(2, '0');
		  minutes = minutes.toString().padStart(2, '0');

		  // 返回格式化的时间字符串
		  return hours + ':' + minutes;
	}
  }
};
